import { Toast } from '/@/utils/Message'
import { agreementStatusApi, callbackApi, tokenRefresh, tokenReissue } from "/@/api/index"
import { setCookieToken } from "/@/utils/cookieMethods"
export function agreementStatus():Promise<boolean> { // 查看是否有未同意的协议
    return new Promise((resolve) => {
        agreementStatusApi().then((res:any) => {
            if(res.code == 200) {
                if(res.data.length > 0) {// 有协议跳转到协议页面
                    sessionStorage.setItem("content",JSON.stringify(res.data))
                    resolve(true)
                }else if(res.data.length == 0) { // 无协议跳转到医联
                    resolve(false)
                }
            }else {
                Toast(res.msg)
            }
        })
    })
}
export function loginCallBack(transactionId:string):Promise<string> { // 走信息确认页面成功之后的回调
    return new Promise((resolve, reject) => {
        callbackApi(transactionId).then(async(res:any) => {
            if(res.code == 200) {
                // 存储 token accessToken 就是老的token  refreshToken是用来刷新token用的
                await setSessionStorage(res)
                resolve("")
            }else {
                Toast(res.msg)
                reject(res.msg)
            }
        })
    })
}
export function tokenRefreshApi():Promise<string> { // 刷新token
    return new Promise((resolve) => {
        tokenRefresh().then(async(res:any) => {
            if(res.data.refreshToken && res.data.accessToken) { //  token 有效
                await setSessionStorage(res)
                await setCookieToken()
                resolve("success")
            }else { // 其他 
                resolve('403')
            }
        })
    })
}

export function tokenReissueApi(smsCode:string):Promise<string> { // 短信验证后 重新签发token
    return new Promise((resolve, reject) => {
        tokenReissue(smsCode).then(async(res:any) => {
            if(res.code == 200) {
                await setSessionStorage(res)
                resolve("success")
            }else {
                reject(res.msg)
            }
        })
    })
}

// 存储 token accessToken 就是老的token  refreshToken是用来刷新token用的
async function setSessionStorage(res:any) { 
    sessionStorage.setItem("token", res.data.accessToken)
    sessionStorage.setItem("accessToken", res.data.accessToken)
    sessionStorage.setItem("refreshToken", res.data.refreshToken) 
    sessionStorage.setItem("expiresIn", res.data.expiresIn)  
    sessionStorage.setItem("lapsesIn", res.data.lapsesIn)
    sessionStorage.setItem("identifier", res.data.identifier) 
    if(res.data.redirectUri) {
        sessionStorage.setItem("redirectUri", res.data.redirectUri)
    }           
}

